// pages/online-refund/online-refund.js
Page({
  	data: {
		patientInfo: {
			name: '',
			relation: '本人',
			idNumber: ''
		},
		showPatientModal: false,
		patientList: [],
		cardBalance: '4100.00', // 与充值页面保持一致
		refundAmount: ''
	},

  onLoad(options) {
    console.log('在线退款页面加载');
    this.loadPatientInfo();
  },

  // 加载就诊人信息
  loadPatientInfo() {
    wx.request({
      url: 'http://localhost:8005/patient/list',
      method: 'GET',
      header: { 'Content-Type': 'application/json' },
      success: (res) => {
        if (res.statusCode === 200 && res.data) {
          let list = res.data
          if (typeof list === 'string') {
            try { list = JSON.parse(list) } catch (e) { return }
          }
          if (list.code !== undefined) list = list.data
          if (!Array.isArray(list)) return
          
          // 保存完整的就诊人列表
          const mapped = list.map(p => ({
            id: p.id,
            name: p.name,
            relation: p.relationTypeName || '本人',
            idNumber: (p.idCardNumber || '').replace(/(\w{3})\w+(\w{2})/, '$1********$2')
          }))
          
          this.setData({ patientList: mapped })
          
          // 找到默认就诊人
          const defaultPatient = list.find(p => p.isDefault === 1)
          if (defaultPatient) {
            this.setData({
              patientInfo: {
                name: defaultPatient.name,
                relation: defaultPatient.relationTypeName || '本人',
                idNumber: (defaultPatient.idCardNumber || '').replace(/(\w{3})\w+(\w{2})/, '$1********$2')
              }
            })
          } else {
            // 如果没有默认就诊人，使用第一个就诊人
            const firstPatient = list[0]
            if (firstPatient) {
              this.setData({
                patientInfo: {
                  name: firstPatient.name,
                  relation: firstPatient.relationTypeName || '本人',
                  idNumber: (firstPatient.idCardNumber || '').replace(/(\w{3})\w+(\w{2})/, '$1********$2')
                }
              })
            }
          }
        }
      }
    })
  },

  // 切换就诊人
  switchPatient() {
    this.setData({
      showPatientModal: true
    });
  },

  // 关闭就诊人模态框
  closePatientModal() {
    this.setData({
      showPatientModal: false
    });
  },

  // 阻止事件冒泡
  stopPropagation() {
    // 阻止事件冒泡
  },

  // 选择就诊人
  selectPatient(e) {
    const patient = e.currentTarget.dataset.patient;
    console.log('选择了就诊人:', patient);
    
    this.setData({
      patientInfo: patient,
      showPatientModal: false
    });

    // 保存到本地存储
    const cacheUser = wx.getStorageSync('userInfo') || {}
    wx.setStorageSync('userInfo', { ...cacheUser, patientId: patient.id })
  },

  // 退款金额输入
  onRefundAmountInput(e) {
    const value = e.detail.value;
    // 限制只能输入数字和小数点
    const filteredValue = value.replace(/[^\d.]/g, '');
    // 限制小数点后两位
    const parts = filteredValue.split('.');
    if (parts.length > 2) {
      return;
    }
    if (parts[1] && parts[1].length > 2) {
      return;
    }
    
    this.setData({
      refundAmount: filteredValue
    });
  },

  // 退款全部金额
  refundAll() {
    this.setData({
      refundAmount: this.data.cardBalance
    });
  },

  	// 确认退款
	confirmRefund() {
		const refundAmount = parseFloat(this.data.refundAmount);
		const cardBalance = parseFloat(this.data.cardBalance);
		
		if (!refundAmount || refundAmount <= 0) {
			wx.showToast({
				title: '请输入有效的退款金额',
				icon: 'none'
			});
			return;
		}
		
		if (refundAmount > cardBalance) {
			wx.showToast({
				title: '退款金额不能超过卡内余额',
				icon: 'none'
			});
			return;
		}
		
		// 显示确认退款弹窗
		wx.showModal({
			title: '确认退款',
			content: `确定要退款 ¥${this.data.refundAmount} 吗？`,
			confirmText: '确认退款',
			cancelText: '取消',
			success: (res) => {
				if (res.confirm) {
					wx.showLoading({
						title: '退款处理中...'
					});
					
					// 模拟退款处理
					setTimeout(() => {
						wx.hideLoading();
						wx.showToast({
							title: '退款成功',
							icon: 'success',
							duration: 2000
						});
						
						// 更新卡内余额
						const newBalance = cardBalance - refundAmount;
						this.setData({
							cardBalance: newBalance.toFixed(2),
							refundAmount: ''
						});
						
						// 延迟返回首页
						setTimeout(() => {
							wx.reLaunch({
								url: '/pages/index/index'
							});
						}, 2000);
					}, 2000);
				}
			}
		});
	}
});
